home *** CD-ROM | disk | FTP | other *** search
/ Skunkware 98 / Skunkware 98.iso / src / mail / pine3.96.tar.gz / pine3.96.tar / pine3.96 / imap / ANSI / c-client / bezerk.c next >
C/C++ Source or Header  |  1996-10-15  |  69KB  |  2,130 lines

  1. /*
  2.  * Program:    Berkeley mail routines
  3.  *
  4.  * Author:    Mark Crispin
  5.  *        Networks and Distributed Computing
  6.  *        Computing & Communications
  7.  *        University of Washington
  8.  *        Administration Building, AG-44
  9.  *        Seattle, WA  98195
  10.  *        Internet: MRC@CAC.Washington.EDU
  11.  *
  12.  * Date:    20 December 1989
  13.  * Last Edited:    15 October 1996
  14.  *
  15.  * Copyright 1996 by the University of Washington
  16.  *
  17.  *  Permission to use, copy, modify, and distribute this software and its
  18.  * documentation for any purpose and without fee is hereby granted, provided
  19.  * that the above copyright notice appears in all copies and that both the
  20.  * above copyright notice and this permission notice appear in supporting
  21.  * documentation, and that the name of the University of Washington not be
  22.  * used in advertising or publicity pertaining to distribution of the software
  23.  * without specific, written prior permission.  This software is made
  24.  * available "as is", and
  25.  * THE UNIVERSITY OF WASHINGTON DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
  26.  * WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT LIMITATION ALL IMPLIED
  27.  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND IN
  28.  * NO EVENT SHALL THE UNIVERSITY OF WASHINGTON BE LIABLE FOR ANY SPECIAL,
  29.  * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  30.  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, TORT
  31.  * (INCLUDING NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF OR IN CONNECTION
  32.  * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  33.  *
  34.  */
  35.  
  36.  
  37. /* Dedication:
  38.  *  This file is dedicated with affection to those Merry Marvels of Musical
  39.  * Madness . . .
  40.  *  ->  The Incomparable Leland Stanford Junior University Marching Band  <-
  41.  * who entertain, awaken, and outrage Stanford fans in the fact of repeated
  42.  * losing seasons and shattered Rose Bowl dreams [Cardinal just don't have
  43.  * HUSKY FEVER!!!].
  44.  *
  45.  */
  46.  
  47. #include <stdio.h>
  48. #include <ctype.h>
  49. #include <errno.h>
  50. extern int errno;        /* just in case */
  51. #include <signal.h>
  52. #include <sys/time.h>        /* must be before osdep.h */
  53. #include "mail.h"
  54. #include "osdep.h"
  55. #include <pwd.h>
  56. #include <sys/stat.h>
  57. #include "bezerk.h"
  58. #include "rfc822.h"
  59. #include "misc.h"
  60. #include "dummy.h"
  61.  
  62. /* Berkeley mail routines */
  63.  
  64.  
  65. /* Driver dispatch used by MAIL */
  66.  
  67. DRIVER bezerkdriver = {
  68.   "bezerk",            /* driver name */
  69.   (DRIVER *) NIL,        /* next driver */
  70.   bezerk_valid,            /* mailbox is valid for us */
  71.   bezerk_parameters,        /* manipulate parameters */
  72.   bezerk_find,            /* find mailboxes */
  73.   bezerk_find_bboards,        /* find bboards */
  74.   bezerk_find_all,        /* find all mailboxes */
  75.   bezerk_find_all_bboards,    /* find all bboards */
  76.   bezerk_subscribe,        /* subscribe to mailbox */
  77.   bezerk_unsubscribe,        /* unsubscribe from mailbox */
  78.   bezerk_subscribe_bboard,    /* subscribe to bboard */
  79.   bezerk_unsubscribe_bboard,    /* unsubscribe from bboard */
  80.   bezerk_create,        /* create mailbox */
  81.   bezerk_delete,        /* delete mailbox */
  82.   bezerk_rename,        /* rename mailbox */
  83.   bezerk_open,            /* open mailbox */
  84.   bezerk_close,            /* close mailbox */
  85.   bezerk_fetchfast,        /* fetch message "fast" attributes */
  86.   bezerk_fetchflags,        /* fetch message flags */
  87.   bezerk_fetchstructure,    /* fetch message envelopes */
  88.   bezerk_fetchheader,        /* fetch message header only */
  89.   bezerk_fetchtext,        /* fetch message body only */
  90.   bezerk_fetchbody,        /* fetch message body section */
  91.   bezerk_setflag,        /* set message flag */
  92.   bezerk_clearflag,        /* clear message flag */
  93.   bezerk_search,        /* search for message based on criteria */
  94.   bezerk_ping,            /* ping mailbox to see if still alive */
  95.   bezerk_check,            /* check for new messages */
  96.   bezerk_expunge,        /* expunge deleted messages */
  97.   bezerk_copy,            /* copy messages to another mailbox */
  98.   bezerk_move,            /* move messages to another mailbox */
  99.   bezerk_append,        /* append string message to mailbox */
  100.   bezerk_gc            /* garbage collect stream */
  101. };
  102.  
  103.                 /* prototype stream */
  104. MAILSTREAM bezerkproto = {&bezerkdriver};
  105.  
  106.                 /* driver parameters */
  107. static long bezerk_fromwidget = T;
  108.  
  109. /* Berkeley mail validate mailbox
  110.  * Accepts: mailbox name
  111.  * Returns: our driver if name is valid, NIL otherwise
  112.  */
  113.  
  114. DRIVER *bezerk_valid (char *name)
  115. {
  116.   char tmp[MAILTMPLEN];
  117.   return bezerk_isvalid (name,tmp) ? &bezerkdriver : NIL;
  118. }
  119.  
  120.  
  121. /* Berkeley mail test for valid mailbox name
  122.  * Accepts: mailbox name
  123.  *        scratch buffer
  124.  * Returns: T if valid, NIL otherwise
  125.  */
  126.  
  127. int bezerk_isvalid (char *name,char *tmp)
  128. {
  129.   int fd;
  130.   int ret = NIL;
  131.   char *t,file[MAILTMPLEN];
  132.   struct stat sbuf;
  133.   time_t tp[2];
  134.   errno = EINVAL;        /* assume invalid argument */
  135.                 /* must be non-empty file */
  136.   if ((*name != '{') && !((*name == '*') && (name[1] == '{')) &&
  137.       (t = dummy_file (file,name)) && !stat (t,&sbuf)) {
  138.     if (!sbuf.st_size)errno = 0;/* empty file */
  139.     else if ((fd = open (file,O_RDONLY,NIL)) >= 0) {
  140.                 /* error -1 for invalid format */
  141.       if (!(ret = bezerk_isvalid_fd (fd,tmp))) errno = -1;
  142.       close (fd);        /* close the file */
  143.       tp[0] = sbuf.st_atime;    /* preserve atime and mtime */
  144.       tp[1] = sbuf.st_mtime;
  145.       utime (file,tp);        /* set the times */
  146.     }
  147.   }
  148.   return ret;            /* return what we should */
  149. }
  150.  
  151. /* Berkeley mail test for valid mailbox
  152.  * Accepts: file descriptor
  153.  *        scratch buffer
  154.  * Returns: T if valid, NIL otherwise
  155.  */
  156.  
  157. long bezerk_isvalid_fd (int fd,char *tmp)
  158. {
  159.   int zn;
  160.   int ret = NIL;
  161.   char *s,*t,c = '\n';
  162.   memset (tmp,'\0',MAILTMPLEN);
  163.   if (read (fd,tmp,MAILTMPLEN-1) >= 0) {
  164.     for (s = tmp; (*s == '\n') || (*s == ' ') || (*s == '\t');) c = *s++;
  165.     if (c == '\n') VALID (s,t,ret,zn);
  166.   }
  167.   return ret;            /* return what we should */
  168. }
  169.  
  170.  
  171. /* Berkeley manipulate driver parameters
  172.  * Accepts: function code
  173.  *        function-dependent value
  174.  * Returns: function-dependent return value
  175.  */
  176.  
  177. void *bezerk_parameters (long function,void *value)
  178. {
  179.   switch ((int) function) {
  180.   case SET_FROMWIDGET:
  181.     bezerk_fromwidget = (long) value;
  182.     break;
  183.   case GET_FROMWIDGET:
  184.     value = (void *) bezerk_fromwidget;
  185.     break;
  186.   default:
  187.     value = NIL;        /* error case */
  188.     break;
  189.   }
  190.   return value;
  191. }
  192.  
  193. /* Berkeley mail find list of mailboxes
  194.  * Accepts: mail stream
  195.  *        pattern to search
  196.  */
  197.  
  198. void bezerk_find (MAILSTREAM *stream,char *pat)
  199. {
  200.   if (stream) dummy_find (NIL,pat);
  201. }
  202.  
  203.  
  204. /* Berkeley mail find list of bboards
  205.  * Accepts: mail stream
  206.  *        pattern to search
  207.  */
  208.  
  209. void bezerk_find_bboards (MAILSTREAM *stream,char *pat)
  210. {
  211.   if (stream) dummy_find_bboards (NIL,pat);
  212. }
  213.  
  214.  
  215. /* Berkeley mail find list of all mailboxes
  216.  * Accepts: mail stream
  217.  *        pattern to search
  218.  */
  219.  
  220. void bezerk_find_all (MAILSTREAM *stream,char *pat)
  221. {
  222.   if (stream) dummy_find_all (NIL,pat);
  223. }
  224.  
  225.  
  226. /* Berkeley mail find list of all bboards
  227.  * Accepts: mail stream
  228.  *        pattern to search
  229.  */
  230.  
  231. void bezerk_find_all_bboards (MAILSTREAM *stream,char *pat)
  232. {
  233.   if (stream) dummy_find_all_bboards (NIL,pat);
  234. }
  235.  
  236. /* Berkeley mail subscribe to mailbox
  237.  * Accepts: mail stream
  238.  *        mailbox to add to subscription list
  239.  * Returns: T on success, NIL on failure
  240.  */
  241.  
  242. long bezerk_subscribe (MAILSTREAM *stream,char *mailbox)
  243. {
  244.   char tmp[MAILTMPLEN];
  245.   return sm_subscribe (dummy_file (tmp,mailbox));
  246. }
  247.  
  248.  
  249. /* Berkeley mail unsubscribe to mailbox
  250.  * Accepts: mail stream
  251.  *        mailbox to delete from subscription list
  252.  * Returns: T on success, NIL on failure
  253.  */
  254.  
  255. long bezerk_unsubscribe (MAILSTREAM *stream,char *mailbox)
  256. {
  257.   char tmp[MAILTMPLEN];
  258.   return sm_unsubscribe (dummy_file (tmp,mailbox));
  259. }
  260.  
  261.  
  262. /* Berkeley mail subscribe to bboard
  263.  * Accepts: mail stream
  264.  *        bboard to add to subscription list
  265.  * Returns: T on success, NIL on failure
  266.  */
  267.  
  268. long bezerk_subscribe_bboard (MAILSTREAM *stream,char *mailbox)
  269. {
  270.   return NIL;            /* never valid for Bezerk */
  271. }
  272.  
  273.  
  274. /* Berkeley mail unsubscribe to bboard
  275.  * Accepts: mail stream
  276.  *        bboard to delete from subscription list
  277.  * Returns: T on success, NIL on failure
  278.  */
  279.  
  280. long bezerk_unsubscribe_bboard (MAILSTREAM *stream,char *mailbox)
  281. {
  282.   return NIL;            /* never valid for Bezerk */
  283. }
  284.  
  285. /* Berkeley mail create mailbox
  286.  * Accepts: MAIL stream
  287.  *        mailbox name to create
  288.  * Returns: T on success, NIL on failure
  289.  */
  290.  
  291. long bezerk_create (MAILSTREAM *stream,char *mailbox)
  292. {
  293.   return dummy_create (stream,mailbox);
  294. }
  295.  
  296.  
  297. /* Berkeley mail delete mailbox
  298.  * Accepts: MAIL stream
  299.  *        mailbox name to delete
  300.  * Returns: T on success, NIL on failure
  301.  */
  302.  
  303. long bezerk_delete (MAILSTREAM *stream,char *mailbox)
  304. {
  305.   return bezerk_rename (stream,mailbox,NIL);
  306. }
  307.  
  308. /* Berkeley mail rename mailbox
  309.  * Accepts: MAIL stream
  310.  *        old mailbox name
  311.  *        new mailbox name (or NIL for delete)
  312.  * Returns: T on success, NIL on failure
  313.  */
  314.  
  315. long bezerk_rename (MAILSTREAM *stream,char *old,char *new)
  316. {
  317.   long ret = T;
  318.   char tmp[MAILTMPLEN],file[MAILTMPLEN],lock[MAILTMPLEN],lockx[MAILTMPLEN];
  319.   int fd,ld;
  320.                 /* get the c-client lock */
  321.   if (!lockname (lock,dummy_file (file,old))) return NIL;
  322.   if ((ld = open (lock,O_RDWR|O_CREAT,
  323.           (int) mail_parameters (NIL,GET_LOCKPROTECTION,NIL))) < 0) {
  324.     sprintf (tmp,"Can't get lock for mailbox %s: %s",old,strerror (errno));
  325.     mm_log (tmp,ERROR);
  326.     return NIL;
  327.   }
  328.                 /* lock out other c-clients */
  329.   if (flock (ld,LOCK_EX|LOCK_NB)) {
  330.     close (ld);            /* couldn't lock, give up on it then */
  331.     sprintf (tmp,"Mailbox %s is in use by another process",old);
  332.     mm_log (tmp,ERROR);
  333.     return NIL;
  334.   }
  335.                 /* lock out non c-client applications */
  336.   if ((fd = bezerk_lock (file,O_RDWR,S_IREAD|S_IWRITE,lockx,LOCK_EX)) < 0) {
  337.     sprintf (tmp,"Can't lock mailbox %s: %s",old,strerror (errno));
  338.     mm_log (tmp,ERROR);
  339.     return NIL;
  340.   }
  341.                 /* do the rename or delete operation */
  342.   if (new ? rename (file,dummy_file (tmp,new)) : unlink (file)) {
  343.     sprintf (tmp,"Can't %s mailbox %s: %s",new ? "rename" : "delete",old,
  344.          strerror (errno));
  345.     mm_log (tmp,ERROR);
  346.     ret = NIL;            /* set failure */
  347.   }
  348.   bezerk_unlock (fd,NIL,lockx);    /* unlock and close mailbox */
  349.   flock (ld,LOCK_UN);        /* release c-client lock lock */
  350.   close (ld);            /* close c-client lock */
  351.   unlink (lock);        /* and delete it */
  352.   return ret;            /* return success */
  353. }
  354.  
  355. /* Berkeley mail open
  356.  * Accepts: Stream to open
  357.  * Returns: Stream on success, NIL on failure
  358.  */
  359.  
  360. MAILSTREAM *bezerk_open (MAILSTREAM *stream)
  361. {
  362.   long i;
  363.   int fd;
  364.   char tmp[MAILTMPLEN];
  365.   struct stat sbuf;
  366.   long retry;
  367.                 /* return prototype for OP_PROTOTYPE call */
  368.   if (!stream) return &bezerkproto;
  369.   retry = stream->silent ? 1 : KODRETRY;
  370.   if (LOCAL) {            /* close old file if stream being recycled */
  371.     bezerk_close (stream);    /* dump and save the changes */
  372.     stream->dtb = &bezerkdriver;/* reattach this driver */
  373.     mail_free_cache (stream);    /* clean up cache */
  374.   }
  375.   stream->local = fs_get (sizeof (BEZERKLOCAL));
  376.                 /* canonicalize the stream mailbox name */
  377.   dummy_file (tmp,stream->mailbox);
  378.                 /* force readonly if bboard */
  379.   if (*stream->mailbox == '*') stream->rdonly = T;
  380.   else {            /* canonicalize name */
  381.     fs_give ((void **) &stream->mailbox);
  382.     stream->mailbox = cpystr (tmp);
  383.   }
  384.   /* You may wonder why LOCAL->name is needed.  It isn't at all obvious from
  385.    * the code.  The problem is that when a stream is recycled with another
  386.    * mailbox of the same type, the driver's close method isn't called because
  387.    * it could be IMAP and closing then would defeat the entire point of
  388.    * recycling.  Hence there is code in the file drivers to call the close
  389.    * method such as what appears above.  The problem is, by this point,
  390.    * mail_open() has already changed the stream->mailbox name to point to the
  391.    * new name, and bezerk_close() needs the old name.
  392.    */
  393.   LOCAL->name = cpystr (tmp);    /* local copy for recycle case */
  394.   LOCAL->ld = NIL;        /* no state locking yet */
  395.   LOCAL->lname = NIL;
  396.   LOCAL->filesize = 0;        /* initialize file information */
  397.   LOCAL->filetime = 0;
  398.   LOCAL->msgs = NIL;        /* no cache yet */
  399.   LOCAL->cachesize = 0;
  400.   LOCAL->buf = (char *) fs_get ((LOCAL->buflen = CHUNK) + 1);
  401.   stream->sequence++;        /* bump sequence number */
  402.  
  403.   LOCAL->dirty = NIL;        /* no update yet */
  404.                 /* make lock for read/write access */
  405.   if (!stream->rdonly) while (retry) {
  406.                 /* get a new file handle each time */
  407.     if (!lockname (tmp,LOCAL->name) ||
  408.     ((fd = open (tmp,O_RDWR|O_CREAT,
  409.             (int) mail_parameters (NIL,GET_LOCKPROTECTION,NIL))) < 0)){
  410.       mm_log ("Can't open mailbox lock, access is readonly",WARN);
  411.       retry = 0;        /* give up */
  412.     }
  413.                 /* can get the lock? */
  414.     else if (flock (fd,LOCK_EX|LOCK_NB)) {
  415.       if (retry-- == KODRETRY) {/* no, first time through? */
  416.                 /* yes, get other process' PID */
  417.     if (!fstat (fd,&sbuf) && (i = min (sbuf.st_size,MAILTMPLEN)) &&
  418.         (read (fd,tmp,i) == i) && !(tmp[i] = 0) && (i = atol (tmp))) {
  419.       kill ((int) i,SIGUSR2);
  420.       sprintf (tmp,"Trying to get mailbox lock from process %ld",i);
  421.       mm_log (tmp,WARN);
  422.     }
  423.     else retry = 0;        /* give up */
  424.       }
  425.       close (fd);        /* get a new handle next time around */
  426.       if (!stream->silent) {    /* nothing if silent stream */
  427.     if (retry) sleep (1);    /* wait a second before trying again */
  428.     else mm_log ("Mailbox is open by another process, access is readonly",
  429.              WARN);
  430.       }
  431.     }
  432.     else {            /* got the lock, nobody else can alter state */
  433.       LOCAL->ld = fd;        /* note lock's fd and name */
  434.       LOCAL->lname = cpystr (tmp);
  435.                 /* make sure mode OK (don't use fchmod()) */
  436.       chmod (LOCAL->lname,(int) mail_parameters (NIL,GET_LOCKPROTECTION,NIL));
  437.       if (stream->silent) i = 0;/* silent streams won't accept KOD */
  438.       else {            /* note our PID in the lock */
  439.     sprintf (tmp,"%d",getpid ());
  440.     write (fd,tmp,(i = strlen (tmp))+1);
  441.       }
  442.       ftruncate (fd,i);        /* make sure tied off */
  443.       fsync (fd);        /* make sure it's available */
  444.       retry = 0;        /* no more need to try */
  445.     }
  446.   }
  447.  
  448.                 /* parse mailbox */
  449.   stream->nmsgs = stream->recent = 0;
  450.                 /* will we be able to get write access? */
  451.   if (LOCAL->ld && access (LOCAL->name,W_OK) && (errno == EACCES)) {
  452.     mm_log ("Can't get write access to mailbox, access is readonly",WARN);
  453.     flock (LOCAL->ld,LOCK_UN);    /* release the lock */
  454.     close (LOCAL->ld);        /* close the lock file */
  455.     LOCAL->ld = NIL;        /* no more lock fd */
  456.     unlink (LOCAL->lname);    /* delete it */
  457.     fs_give ((void **) &LOCAL->lname);
  458.   }
  459.                 /* abort if can't get RW silent stream */
  460.   if (stream->silent && !stream->rdonly && !LOCAL->ld) bezerk_abort (stream);
  461.                 /* parse mailbox */
  462.   else if ((fd = bezerk_parse (stream,tmp,LOCK_SH)) >= 0) {
  463.     bezerk_unlock (fd,stream,tmp);
  464.     mail_unlock (stream);
  465.   }
  466.   if (!LOCAL) return NIL;    /* failure if stream died */
  467.   stream->rdonly = !LOCAL->ld;    /* make sure upper level knows readonly */
  468.                 /* notify about empty mailbox */
  469.   if (!(stream->nmsgs || stream->silent)) mm_log ("Mailbox is empty",NIL);
  470.   return stream;        /* return stream alive to caller */
  471. }
  472.  
  473. /* Berkeley mail close
  474.  * Accepts: MAIL stream
  475.  */
  476.  
  477. void bezerk_close (MAILSTREAM *stream)
  478. {
  479.   int silent = stream->silent;
  480.   stream->silent = T;        /* note this stream is dying */
  481.   bezerk_check (stream);    /* dump final checkpoint */
  482.   stream->silent = silent;    /* restore previous status */
  483.   bezerk_abort (stream);    /* now punt the file and local data */
  484. }
  485.  
  486.  
  487. /* Berkeley mail fetch fast information
  488.  * Accepts: MAIL stream
  489.  *        sequence
  490.  */
  491.  
  492. void bezerk_fetchfast (MAILSTREAM *stream,char *sequence)
  493. {
  494.   return;            /* no-op for local mail */
  495. }
  496.  
  497.  
  498. /* Berkeley mail fetch flags
  499.  * Accepts: MAIL stream
  500.  *        sequence
  501.  */
  502.  
  503. void bezerk_fetchflags (MAILSTREAM *stream,char *sequence)
  504. {
  505.   return;            /* no-op for local mail */
  506. }
  507.  
  508. /* Berkeley mail fetch structure
  509.  * Accepts: MAIL stream
  510.  *        message # to fetch
  511.  *        pointer to return body
  512.  * Returns: envelope of this message, body returned in body value
  513.  *
  514.  * Fetches the "fast" information as well
  515.  */
  516.  
  517. ENVELOPE *bezerk_fetchstructure (MAILSTREAM *stream,long msgno,BODY **body)
  518. {
  519.   ENVELOPE **env;
  520.   BODY **b;
  521.   STRING bs;
  522.   LONGCACHE *lelt;
  523.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  524.   long i = max (m->headersize,m->bodysize);
  525.   if (stream->scache) {        /* short cache */
  526.     if (msgno != stream->msgno){/* flush old poop if a different message */
  527.       mail_free_envelope (&stream->env);
  528.       mail_free_body (&stream->body);
  529.     }
  530.     stream->msgno = msgno;
  531.     env = &stream->env;        /* get pointers to envelope and body */
  532.     b = &stream->body;
  533.   }
  534.   else {            /* long cache */
  535.     lelt = mail_lelt (stream,msgno);
  536.     env = &lelt->env;        /* get pointers to envelope and body */
  537.     b = &lelt->body;
  538.   }
  539.   if ((body && !*b) || !*env) {    /* have the poop we need? */
  540.     mail_free_envelope (env);    /* flush old envelope and body */
  541.     mail_free_body (b);
  542.     if (i > LOCAL->buflen) {    /* make sure enough buffer space */
  543.       fs_give ((void **) &LOCAL->buf);
  544.       LOCAL->buf = (char *) fs_get ((LOCAL->buflen = i) + 1);
  545.     }
  546.     INIT (&bs,mail_string,(void *) m->body,m->bodysize);
  547.                 /* parse envelope and body */
  548.     rfc822_parse_msg (env,body ? b : NIL,m->header,m->headersize,&bs,
  549.               mylocalhost (),LOCAL->buf);
  550.   }
  551.   if (body) *body = *b;        /* return the body */
  552.   return *env;            /* return the envelope */
  553. }
  554.  
  555. /* Berkeley mail snarf message, only for Tenex driver
  556.  * Accepts: MAIL stream
  557.  *        message # to snarf
  558.  *        pointer to size to return
  559.  * Returns: message text in RFC822 format
  560.  */
  561.  
  562. char *bezerk_snarf (MAILSTREAM *stream,long msgno,long *size)
  563. {
  564.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  565.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  566.   if (((*size = m->headersize + m->bodysize) > LOCAL->buflen) ||
  567.       LOCAL->buflen > CHUNK) {    /* make sure stream can hold the text */
  568.                 /* fs_resize would do an unnecessary copy */
  569.     fs_give ((void **) &LOCAL->buf);
  570.     LOCAL->buf = (char *) fs_get((LOCAL->buflen = max (*size,(long) CHUNK))+1);
  571.   }
  572.                 /* copy the text */
  573.   if (m->headersize) memcpy (LOCAL->buf,m->header,m->headersize);
  574.   if (m->bodysize) memcpy (LOCAL->buf + m->headersize,m->body,m->bodysize);
  575.   LOCAL->buf[*size] = '\0';    /* tie off string */
  576.   return LOCAL->buf;
  577. }
  578.  
  579. /* Berkeley mail fetch message header
  580.  * Accepts: MAIL stream
  581.  *        message # to fetch
  582.  * Returns: message header in RFC822 format
  583.  */
  584.  
  585. char *bezerk_fetchheader (MAILSTREAM *stream,long msgno)
  586. {
  587.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  588.                 /* copy the string */
  589.   strcrlfcpy (&LOCAL->buf,&LOCAL->buflen,m->header,m->headersize);
  590.   return LOCAL->buf;
  591. }
  592.  
  593.  
  594. /* Berkeley mail fetch message text (body only)
  595.  * Accepts: MAIL stream
  596.  *        message # to fetch
  597.  * Returns: message text in RFC822 format
  598.  */
  599.  
  600. char *bezerk_fetchtext (MAILSTREAM *stream,long msgno)
  601. {
  602.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  603.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  604.   if (!elt->seen) {        /* if message not seen */
  605.     elt->seen = T;        /* mark message as seen */
  606.                 /* recalculate Status/X-Status lines */
  607.     bezerk_update_status (m->status,elt);
  608.     LOCAL->dirty = T;        /* note stream is now dirty */
  609.   }
  610.   strcrlfcpy (&LOCAL->buf,&LOCAL->buflen,m->body,m->bodysize);
  611.   return LOCAL->buf;
  612. }
  613.  
  614. /* Berkeley fetch message body as a structure
  615.  * Accepts: Mail stream
  616.  *        message # to fetch
  617.  *        section specifier
  618.  *        pointer to length
  619.  * Returns: pointer to section of message body
  620.  */
  621.  
  622. char *bezerk_fetchbody (MAILSTREAM *stream,long m,char *s,unsigned long *len)
  623. {
  624.   BODY *b;
  625.   PART *pt;
  626.   unsigned long i;
  627.   char *base = LOCAL->msgs[m - 1]->body;
  628.   unsigned long offset = 0;
  629.   MESSAGECACHE *elt = mail_elt (stream,m);
  630.                 /* make sure have a body */
  631.   if (!(bezerk_fetchstructure (stream,m,&b) && b && s && *s &&
  632.     ((i = strtol (s,&s,10)) > 0))) return NIL;
  633.   do {                /* until find desired body part */
  634.                 /* multipart content? */
  635.     if (b->type == TYPEMULTIPART) {
  636.       pt = b->contents.part;    /* yes, find desired part */
  637.       while (--i && (pt = pt->next));
  638.       if (!pt) return NIL;    /* bad specifier */
  639.                 /* note new body, check valid nesting */
  640.       if (((b = &pt->body)->type == TYPEMULTIPART) && !*s) return NIL;
  641.       offset = pt->offset;    /* get new offset */
  642.     }
  643.     else if (i != 1) return NIL;/* otherwise must be section 1 */
  644.                 /* need to go down further? */
  645.     if (i = *s) switch (b->type) {
  646.     case TYPEMESSAGE:        /* embedded message */
  647.       offset = b->contents.msg.offset;
  648.       b = b->contents.msg.body;    /* get its body, drop into multipart case */
  649.     case TYPEMULTIPART:        /* multipart, get next section */
  650.       if ((*s++ == '.') && (i = strtol (s,&s,10)) > 0) break;
  651.     default:            /* bogus subpart specification */
  652.       return NIL;
  653.     }
  654.   } while (i);
  655.                 /* lose if body bogus */
  656.   if ((!b) || b->type == TYPEMULTIPART) return NIL;
  657.   if (!elt->seen) {        /* if message not seen */
  658.     elt->seen = T;        /* mark message as seen */
  659.                 /* recalculate Status/X-Status lines */
  660.     bezerk_update_status (LOCAL->msgs[m - 1]->status,elt);
  661.     LOCAL->dirty = T;        /* note stream is now dirty */
  662.   }
  663.   return rfc822_contents (&LOCAL->buf,&LOCAL->buflen,len,base + offset,
  664.               b->size.ibytes,b->encoding);
  665. }
  666.  
  667. /* Berkeley mail set flag
  668.  * Accepts: MAIL stream
  669.  *        sequence
  670.  *        flag(s)
  671.  */
  672.  
  673. void bezerk_setflag (MAILSTREAM *stream,char *sequence,char *flag)
  674. {
  675.   MESSAGECACHE *elt;
  676.   long i;
  677.   short f = bezerk_getflags (stream,flag);
  678.   if (!f) return;        /* no-op if no flags to modify */
  679.                 /* get sequence and loop on it */
  680.   if (mail_sequence (stream,sequence)) for (i = 1; i <= stream->nmsgs; i++)
  681.     if ((elt = mail_elt (stream,i))->sequence) {
  682.                 /* set all requested flags */
  683.       if (f&fSEEN) elt->seen = T;
  684.       if (f&fDELETED) elt->deleted = T;
  685.       if (f&fFLAGGED) elt->flagged = T;
  686.       if (f&fANSWERED) elt->answered = T;
  687.                 /* recalculate Status/X-Status lines */
  688.       bezerk_update_status (LOCAL->msgs[i - 1]->status,elt);
  689.       LOCAL->dirty = T;        /* note stream is now dirty */
  690.     }
  691. }
  692.  
  693.  
  694. /* Berkeley mail clear flag
  695.  * Accepts: MAIL stream
  696.  *        sequence
  697.  *        flag(s)
  698.  */
  699.  
  700. void bezerk_clearflag (MAILSTREAM *stream,char *sequence,char *flag)
  701. {
  702.   MESSAGECACHE *elt;
  703.   long i;
  704.   short f = bezerk_getflags (stream,flag);
  705.   if (!f) return;        /* no-op if no flags to modify */
  706.                 /* get sequence and loop on it */
  707.   if (mail_sequence (stream,sequence)) for (i = 1; i <= stream->nmsgs; i++)
  708.     if ((elt = mail_elt (stream,i))->sequence) {
  709.                 /* clear all requested flags */
  710.       if (f&fSEEN) elt->seen = NIL;
  711.       if (f&fDELETED) elt->deleted = NIL;
  712.       if (f&fFLAGGED) elt->flagged = NIL;
  713.       if (f&fANSWERED) elt->answered = NIL;
  714.                 /* recalculate Status/X-Status lines */
  715.       bezerk_update_status (LOCAL->msgs[i - 1]->status,elt);
  716.       LOCAL->dirty = T;        /* note stream is now dirty */
  717.     }
  718. }
  719.  
  720. /* Berkeley mail search for messages
  721.  * Accepts: MAIL stream
  722.  *        search criteria
  723.  */
  724.  
  725. void bezerk_search (MAILSTREAM *stream,char *criteria)
  726. {
  727.   long i,n;
  728.   char *d;
  729.   search_t f;
  730.                 /* initially all searched */
  731.   for (i = 1; i <= stream->nmsgs; ++i) mail_elt (stream,i)->searched = T;
  732.                 /* get first criterion */
  733.   if (criteria && (criteria = strtok (criteria," "))) {
  734.                 /* for each criterion */
  735.     for (; criteria; (criteria = strtok (NIL," "))) {
  736.       f = NIL; d = NIL; n = 0;    /* init then scan the criterion */
  737.       switch (*ucase (criteria)) {
  738.       case 'A':            /* possible ALL, ANSWERED */
  739.     if (!strcmp (criteria+1,"LL")) f = bezerk_search_all;
  740.     else if (!strcmp (criteria+1,"NSWERED")) f = bezerk_search_answered;
  741.     break;
  742.       case 'B':            /* possible BCC, BEFORE, BODY */
  743.     if (!strcmp (criteria+1,"CC"))
  744.       f = bezerk_search_string (bezerk_search_bcc,&d,&n);
  745.     else if (!strcmp (criteria+1,"EFORE"))
  746.       f = bezerk_search_date (bezerk_search_before,&n);
  747.     else if (!strcmp (criteria+1,"ODY"))
  748.       f = bezerk_search_string (bezerk_search_body,&d,&n);
  749.     break;
  750.       case 'C':            /* possible CC */
  751.     if (!strcmp (criteria+1,"C")) 
  752.       f = bezerk_search_string (bezerk_search_cc,&d,&n);
  753.     break;
  754.       case 'D':            /* possible DELETED */
  755.     if (!strcmp (criteria+1,"ELETED")) f = bezerk_search_deleted;
  756.     break;
  757.       case 'F':            /* possible FLAGGED, FROM */
  758.     if (!strcmp (criteria+1,"LAGGED")) f = bezerk_search_flagged;
  759.     else if (!strcmp (criteria+1,"ROM"))
  760.       f = bezerk_search_string (bezerk_search_from,&d,&n);
  761.     break;
  762.       case 'K':            /* possible KEYWORD */
  763.     if (!strcmp (criteria+1,"EYWORD"))
  764.       f = bezerk_search_flag (bezerk_search_keyword,&d);
  765.     break;
  766.       case 'N':            /* possible NEW */
  767.     if (!strcmp (criteria+1,"EW")) f = bezerk_search_new;
  768.     break;
  769.  
  770.       case 'O':            /* possible OLD, ON */
  771.     if (!strcmp (criteria+1,"LD")) f = bezerk_search_old;
  772.     else if (!strcmp (criteria+1,"N"))
  773.       f = bezerk_search_date (bezerk_search_on,&n);
  774.     break;
  775.       case 'R':            /* possible RECENT */
  776.     if (!strcmp (criteria+1,"ECENT")) f = bezerk_search_recent;
  777.     break;
  778.       case 'S':            /* possible SEEN, SINCE, SUBJECT */
  779.     if (!strcmp (criteria+1,"EEN")) f = bezerk_search_seen;
  780.     else if (!strcmp (criteria+1,"INCE"))
  781.       f = bezerk_search_date (bezerk_search_since,&n);
  782.     else if (!strcmp (criteria+1,"UBJECT"))
  783.       f = bezerk_search_string (bezerk_search_subject,&d,&n);
  784.     break;
  785.       case 'T':            /* possible TEXT, TO */
  786.     if (!strcmp (criteria+1,"EXT"))
  787.       f = bezerk_search_string (bezerk_search_text,&d,&n);
  788.     else if (!strcmp (criteria+1,"O"))
  789.       f = bezerk_search_string (bezerk_search_to,&d,&n);
  790.     break;
  791.       case 'U':            /* possible UN* */
  792.     if (criteria[1] == 'N') {
  793.       if (!strcmp (criteria+2,"ANSWERED")) f = bezerk_search_unanswered;
  794.       else if (!strcmp (criteria+2,"DELETED")) f = bezerk_search_undeleted;
  795.       else if (!strcmp (criteria+2,"FLAGGED")) f = bezerk_search_unflagged;
  796.       else if (!strcmp (criteria+2,"KEYWORD"))
  797.         f = bezerk_search_flag (bezerk_search_unkeyword,&d);
  798.       else if (!strcmp (criteria+2,"SEEN")) f = bezerk_search_unseen;
  799.     }
  800.     break;
  801.       default:            /* we will barf below */
  802.     break;
  803.       }
  804.       if (!f) {            /* if can't determine any criteria */
  805.     sprintf (LOCAL->buf,"Unknown search criterion: %.30s",criteria);
  806.     mm_log (LOCAL->buf,ERROR);
  807.     return;
  808.       }
  809.                 /* run the search criterion */
  810.       for (i = 1; i <= stream->nmsgs; ++i)
  811.     if (mail_elt (stream,i)->searched && !(*f) (stream,i,d,n))
  812.       mail_elt (stream,i)->searched = NIL;
  813.     }
  814.                 /* report search results to main program */
  815.     for (i = 1; i <= stream->nmsgs; ++i)
  816.       if (mail_elt (stream,i)->searched) mail_searched (stream,i);
  817.   }
  818. }
  819.  
  820. /* Berkeley mail ping mailbox
  821.  * Accepts: MAIL stream
  822.  * Returns: T if stream alive, else NIL
  823.  * No-op for readonly files, since read/writer can expunge it from under us!
  824.  */
  825.  
  826. long bezerk_ping (MAILSTREAM *stream)
  827. {
  828.   char lock[MAILTMPLEN];
  829.   struct stat sbuf;
  830.   int fd;
  831.                 /* does he want to give up readwrite? */
  832.   if (stream->rdonly && LOCAL->ld) {
  833.     flock (LOCAL->ld,LOCK_UN);    /* yes, release the lock */
  834.     close (LOCAL->ld);        /* close the lock file */
  835.     LOCAL->ld = NIL;        /* no more lock fd */
  836.     unlink (LOCAL->lname);    /* delete it */
  837.     fs_give ((void **) &LOCAL->lname);
  838.   }
  839.                 /* make sure it is alright to do this at all */
  840.   if (LOCAL && LOCAL->ld && !stream->lock) {
  841.                 /* get current mailbox size */
  842.     stat (LOCAL->name,&sbuf);    /* parse if mailbox changed */
  843.     if ((sbuf.st_size != LOCAL->filesize) &&
  844.     ((fd = bezerk_parse (stream,lock,LOCK_SH)) >= 0)) {
  845.                 /* unlock mailbox */
  846.       bezerk_unlock (fd,stream,lock);
  847.       mail_unlock (stream);    /* and stream */
  848.     }
  849.   }
  850.   return LOCAL ? T : NIL;    /* return if still alive */
  851. }
  852.  
  853. /* Berkeley mail check mailbox
  854.  * Accepts: MAIL stream
  855.  * No-op for readonly files, since read/writer can expunge it from under us!
  856.  */
  857.  
  858. void bezerk_check (MAILSTREAM *stream)
  859. {
  860.   char lock[MAILTMPLEN];
  861.   int fd;
  862.                 /* parse and lock mailbox */
  863.   if (LOCAL && LOCAL->ld && ((fd = bezerk_parse (stream,lock,LOCK_EX)) >= 0)) {
  864.                 /* dump checkpoint if needed */
  865.     if (LOCAL->dirty && bezerk_extend (stream,fd,NIL)) bezerk_save (stream,fd);
  866.                 /* flush locks */
  867.     bezerk_unlock (fd,stream,lock);
  868.     mail_unlock (stream);
  869.   }
  870.   if (LOCAL && LOCAL->ld && !stream->silent) mm_log ("Check completed",NIL);
  871. }
  872.  
  873. /* Berkeley mail expunge mailbox
  874.  * Accepts: MAIL stream
  875.  */
  876.  
  877. void bezerk_expunge (MAILSTREAM *stream)
  878. {
  879.   int fd,j;
  880.   long i = 1;
  881.   long n = 0;
  882.   unsigned long recent;
  883.   MESSAGECACHE *elt;
  884.   char *r = "No messages deleted, so no update needed";
  885.   char lock[MAILTMPLEN];
  886.   if (LOCAL && LOCAL->ld) {    /* parse and lock mailbox */
  887.     if ((fd = bezerk_parse (stream,lock,LOCK_EX)) >= 0) {
  888.       recent = stream->recent;    /* get recent now that new ones parsed */
  889.       while ((j = (i<=stream->nmsgs)) && !(elt = mail_elt (stream,i))->deleted)
  890.     i++;            /* find first deleted message */
  891.       if (j) {            /* found one? */
  892.                 /* make sure we can do the worst case thing */
  893.     if (bezerk_extend (stream,fd,"Unable to expunge mailbox")) {
  894.       do {            /* flush deleted messages */
  895.         if ((elt = mail_elt (stream,i))->deleted) {
  896.                 /* if recent, note one less recent message */
  897.           if (elt->recent) --recent;
  898.                 /* flush local cache entry */
  899.           fs_give ((void **) &LOCAL->msgs[i - 1]);
  900.           for (j = i; j < stream->nmsgs; j++)
  901.         LOCAL->msgs[j - 1] = LOCAL->msgs[j];
  902.           LOCAL->msgs[stream->nmsgs - 1] = NIL;
  903.                 /* notify upper levels */
  904.           mail_expunged (stream,i);
  905.           n++;        /* count another expunged message */
  906.         }
  907.         else i++;        /* otherwise try next message */
  908.       } while (i <= stream->nmsgs);
  909.                 /* dump checkpoint of the results */
  910.       bezerk_save (stream,fd);
  911.       sprintf ((r = LOCAL->buf),"Expunged %d messages",n);
  912.     }
  913.       }
  914.                 /* notify upper level, free locks */
  915.       mail_exists (stream,stream->nmsgs);
  916.       mail_recent (stream,recent);
  917.       bezerk_unlock (fd,stream,lock);
  918.       mail_unlock (stream);
  919.     }
  920.   }
  921.   else r = "Expunge ignored on readonly mailbox";
  922.   if (LOCAL && !stream->silent) mm_log (r,NIL);
  923. }
  924.  
  925. /* Berkeley mail copy message(s)
  926.  * Accepts: MAIL stream
  927.  *        sequence
  928.  *        destination mailbox
  929.  * Returns: T if copy successful, else NIL
  930.  */
  931.  
  932. long bezerk_copy (MAILSTREAM *stream,char *sequence,char *mailbox)
  933. {
  934.                 /* copy the messages */
  935.   return (mail_sequence (stream,sequence)) ?
  936.     bezerk_copy_messages (stream,mailbox) : NIL;
  937. }
  938.  
  939.  
  940. /* Berkeley mail move message(s)
  941.  * Accepts: MAIL stream
  942.  *        sequence
  943.  *        destination mailbox
  944.  * Returns: T if move successful, else NIL
  945.  */
  946.  
  947. long bezerk_move (MAILSTREAM *stream,char *sequence,char *mailbox)
  948. {
  949.   long i;
  950.   MESSAGECACHE *elt;
  951.   if (!(mail_sequence (stream,sequence) &&
  952.     bezerk_copy_messages (stream,mailbox))) return NIL;
  953.                 /* delete all requested messages */
  954.   for (i = 1; i <= stream->nmsgs; i++)
  955.     if ((elt = mail_elt (stream,i))->sequence) {
  956.       elt->deleted = T;        /* mark message deleted */
  957.                 /* recalculate Status/X-Status lines */
  958.       bezerk_update_status (LOCAL->msgs[i - 1]->status,elt);
  959.       LOCAL->dirty = T;        /* note stream is now dirty */
  960.     }
  961.   return T;
  962. }
  963.  
  964. /* Berkeley mail append message from stringstruct
  965.  * Accepts: MAIL stream
  966.  *        destination mailbox
  967.  *        initial flags
  968.  *        internal date
  969.  *        stringstruct of messages to append
  970.  * Returns: T if append successful, else NIL
  971.  */
  972.  
  973. #define BUFLEN 8*MAILTMPLEN
  974.  
  975. long bezerk_append (MAILSTREAM *stream,char *mailbox,char *flags,char *date,
  976.             STRING *message)
  977. {
  978.   struct stat sbuf;
  979.   int i,fd,ti,zn;
  980.   char *s,*x,buf[BUFLEN],file[MAILTMPLEN],lock[MAILTMPLEN];
  981.   time_t tp[2];
  982.   MESSAGECACHE elt;
  983.   char c = '\n';
  984.   long j,n,ok = T;
  985.   time_t t = time (0);
  986.   unsigned long size = SIZE (message);
  987.   short f = bezerk_getflags (stream,flags);
  988.                 /* parse date if given */
  989.   if (date && !mail_parse_date (&elt,date)) {
  990.     sprintf (buf,"Bad date in append: %s",date);
  991.     mm_log (buf,ERROR);
  992.     return NIL;
  993.   }
  994.                 /* make sure valid mailbox */
  995.   if (!bezerk_isvalid (mailbox,buf)) switch (errno) {
  996.   case ENOENT:            /* no such file? */
  997.     if (strcmp (ucase (strcpy (buf,mailbox)),"INBOX")) {
  998.       mm_notify (stream,"[TRYCREATE] Must create mailbox before append",NIL);
  999.       return NIL;
  1000.     }
  1001.     else break;
  1002.   case 0:            /* merely empty file? */
  1003.     break;
  1004.   case EINVAL:
  1005.     sprintf (buf,"Invalid Berkeley-format mailbox name: %s",mailbox);
  1006.     mm_log (buf,ERROR);
  1007.     return NIL;
  1008.   default:
  1009.     sprintf (buf,"Not a Berkeley-format mailbox: %s",mailbox);
  1010.     mm_log (buf,ERROR);
  1011.     return NIL;
  1012.   }
  1013.   if ((fd = bezerk_lock (dummy_file (file,mailbox),O_WRONLY|O_APPEND|O_CREAT,
  1014.              S_IREAD|S_IWRITE,lock,LOCK_EX)) < 0) {
  1015.     sprintf (buf,"Can't open append mailbox: %s",strerror (errno));
  1016.     mm_log (buf,ERROR);
  1017.     return NIL;
  1018.   }
  1019.  
  1020.   mm_critical (stream);        /* go critical */
  1021.   fstat (fd,&sbuf);        /* get current file size */
  1022.   sprintf (buf,"From %s@%s ",myusername (),mylocalhost ());
  1023.                 /* write the date given */
  1024.   if (date) mail_cdate (buf + strlen (buf),&elt);
  1025.   else strcat (buf,ctime (&t));    /* otherwise write the time now */
  1026.   sprintf (buf + strlen (buf),"Status: %sO\nX-Status: %s%s%s\n",
  1027.        f&fSEEN ? "R" : "",f&fDELETED ? "D" : "",
  1028.        f&fFLAGGED ? "F" : "",f&fANSWERED ? "A" : "");
  1029.   i = strlen (buf);        /* initial buffer space used */
  1030.   while (ok && size--) {    /* copy text, tossing out CR's */
  1031.                 /* if at start of line */
  1032.     if ((c == '\n') && (size > 5)) {
  1033.       n = GETPOS (message);    /* prepend a broket if needed */
  1034.       if ((SNX (message) == 'F') && (SNX (message) == 'r') &&
  1035.       (SNX (message) == 'o') && (SNX (message) == 'm') &&
  1036.       (SNX (message) == ' ')) {
  1037.                 /* always write widget if unconditional */
  1038.     if (bezerk_fromwidget) ok = bezerk_append_putc (fd,buf,&i,'>');
  1039.     else {            /* hairier test, count length of this line */
  1040.       for (j = 6; (j < size) && (SNX (message) != '\n'); j++);
  1041.       if (j < size) {    /* copy line */
  1042.         SETPOS (message,n);    /* restore position */
  1043.         x = s = (char *) fs_get (j + 1);
  1044.         while (j--) if ((c = SNX (message)) != '\015') *x++ = c;
  1045.         *x = '\0';        /* tie off line */
  1046.         VALID (s,x,ti,zn);    /* see if looks like need a widget */
  1047.         if (ti) ok = bezerk_append_putc (fd,buf,&i,'>');
  1048.         fs_give ((void **) &s);
  1049.       }
  1050.     }
  1051.       }
  1052.       SETPOS (message,n);    /* restore position as needed */
  1053.     }
  1054.                 /* copy another character */
  1055.     if ((c = SNX (message)) != '\015') ok = bezerk_append_putc (fd,buf,&i,c);
  1056.   }
  1057.                 /* write trailing newline */
  1058.   if (ok) ok = bezerk_append_putc (fd,buf,&i,'\n');
  1059.   if (!(ok && (ok = (write (fd,buf,i) >= 0)) && (ok = !fsync (fd)))) {
  1060.     sprintf (buf,"Message append failed: %s",strerror (errno));
  1061.     mm_log (buf,ERROR);
  1062.     ftruncate (fd,sbuf.st_size);
  1063.   }
  1064.   tp[0] = sbuf.st_atime;    /* preserve atime */
  1065.   tp[1] = time (0);        /* set mtime to now */
  1066.   utime (file,tp);        /* set the times */
  1067.   bezerk_unlock (fd,NIL,lock);    /* unlock and close mailbox */
  1068.   mm_nocritical (stream);    /* release critical */
  1069.   return ok;            /* return success */
  1070. }
  1071.  
  1072. /* Berkeley mail append character
  1073.  * Accepts: file descriptor
  1074.  *        output buffer
  1075.  *        pointer to current size of output buffer
  1076.  *        character to append
  1077.  * Returns: T if append successful, else NIL
  1078.  */
  1079.  
  1080. long bezerk_append_putc (int fd,char *s,int *i,char c)
  1081. {
  1082.   s[(*i)++] = c;
  1083.   if (*i == BUFLEN) {        /* dump if buffer filled */
  1084.     if (write (fd,s,*i) < 0) return NIL;
  1085.     *i = 0;            /* reset */
  1086.   }
  1087.   return T;
  1088. }
  1089.  
  1090. /* Berkeley garbage collect stream
  1091.  * Accepts: Mail stream
  1092.  *        garbage collection flags
  1093.  */
  1094.  
  1095. void bezerk_gc (MAILSTREAM *stream,long gcflags)
  1096. {
  1097.   /* nothing here for now */
  1098. }
  1099.  
  1100. /* Internal routines */
  1101.  
  1102.  
  1103. /* Berkeley mail abort stream
  1104.  * Accepts: MAIL stream
  1105.  */
  1106.  
  1107. void bezerk_abort (MAILSTREAM *stream)
  1108. {
  1109.   long i;
  1110.   if (LOCAL) {            /* only if a file is open */
  1111.     if (LOCAL->name) fs_give ((void **) &LOCAL->name);
  1112.     if (LOCAL->ld) {        /* have a mailbox lock? */
  1113.       flock (LOCAL->ld,LOCK_UN);/* yes, release the lock */
  1114.       close (LOCAL->ld);    /* close the lock file */
  1115.       unlink (LOCAL->lname);    /* and delete it */
  1116.     }
  1117.     fs_give ((void **) &LOCAL->lname);
  1118.     if (LOCAL->msgs) {        /* free local cache */
  1119.       for (i = 0; i < stream->nmsgs; ++i) fs_give ((void **) &LOCAL->msgs[i]);
  1120.       fs_give ((void **) &LOCAL->msgs);
  1121.     }
  1122.                 /* free local text buffers */
  1123.     if (LOCAL->buf) fs_give ((void **) &LOCAL->buf);
  1124.                 /* nuke the local data */
  1125.     fs_give ((void **) &stream->local);
  1126.     stream->dtb = NIL;        /* log out the DTB */
  1127.   }
  1128. }
  1129.  
  1130. /* Berkeley open and lock mailbox
  1131.  * Accepts: file name to open/lock
  1132.  *        file open mode
  1133.  *        destination buffer for lock file name
  1134.  *        type of locking operation (LOCK_SH or LOCK_EX)
  1135.  */
  1136.  
  1137. int bezerk_lock (char *file,int flags,int mode,char *lock,int op)
  1138. {
  1139.   int fd,ld,j;
  1140.   int i = LOCKTIMEOUT * 60 - 1;
  1141.   char hitch[MAILTMPLEN],tmp[MAILTMPLEN];
  1142.   time_t t;
  1143.   struct stat sb;
  1144.                 /* build lock filename */
  1145.   if (chk_notsymlink (strcat (dummy_file (lock,file),".lock"),NIL)) do {
  1146.     t = time (0);        /* get the time now */
  1147. #ifdef NFSKLUDGE
  1148.   /* SUN-OS had an NFS, As kludgy as an albatross;
  1149.    * And everywhere that it was installed, It was a total loss.  -- MRC 9/25/91
  1150.    */
  1151.                 /* build hitching post file name */
  1152.     sprintf (hitch,"%s.%d.%d.",lock,time (0),getpid ());
  1153.     j = strlen (hitch);        /* append local host name */
  1154.     gethostname (hitch + j,(MAILTMPLEN - j) - 1);
  1155.                 /* try to get hitching-post file */
  1156.     if ((ld = open (hitch,O_WRONLY|O_CREAT|O_EXCL,
  1157.             (int) mail_parameters (NIL,GET_LOCKPROTECTION,NIL))) < 0) {
  1158.       sprintf (tmp,"Error creating %s: %s",hitch,strerror (errno));
  1159.       switch (errno) {        /* what happened? */
  1160.       case EEXIST:        /* file already exists? */
  1161.     break;            /* oops, just try again */
  1162.       case EACCES:        /* protection failure */
  1163.                 /* try again if file exists(?) */
  1164.     if (!stat (hitch,&sb)) break;
  1165.                 /* punt silently if paranoid site */
  1166.     if (mail_parameters (NIL,GET_LOCKEACCESERROR,NIL))
  1167.       default:            /* some other error */
  1168.       mm_log (tmp,WARN);    /* this is probably not good */
  1169.     *lock = '\0';        /* give up on lock file */
  1170.     break;
  1171.       }
  1172.     }
  1173.     else {            /* got a hitching-post */
  1174.                 /* make sure others can break the lock */
  1175.       chmod (hitch,(int) mail_parameters (NIL,GET_LOCKPROTECTION,NIL));
  1176.       close (ld);        /* close the hitching-post */
  1177.       link (hitch,lock);    /* tie hitching-post to lock, ignore failure */
  1178.       stat (hitch,&sb);        /* get its data */
  1179.       unlink (hitch);        /* flush hitching post */
  1180.       /* If link count .ne. 2, hitch failed.  Set ld to -1 as if open() failed
  1181.      so we try again.  If extant lock file and time now is .gt. file time
  1182.      plus timeout interval, flush the lock so can win next time around. */
  1183.       if ((ld = (sb.st_nlink != 2) ? -1 : 0) && (!stat (lock,&sb)) &&
  1184.       (t > sb.st_ctime + LOCKTIMEOUT * 60)) unlink (lock);
  1185.     }
  1186.  
  1187. #else
  1188.   /* This works on modern Unix systems which are not afflicted with NFS mail.
  1189.    * "Modern" means that O_EXCL works.  I think that NFS mail is a terrible
  1190.    * idea -- that's what IMAP is for -- but some people insist upon losing...
  1191.    */
  1192.                 /* try to get the lock */
  1193.     if ((ld = open (lock,O_WRONLY|O_CREAT|O_EXCL,
  1194.             (int) mail_parameters (NIL,GET_LOCKPROTECTION,NIL))) < 0)
  1195.       switch (errno) {        /* what happened? */
  1196.       case EEXIST:        /* if extant and old, grab it for ourselves */
  1197.     if ((!stat (lock,&sb)) && t > sb.st_ctime + LOCKTIMEOUT * 60)
  1198.       ld = open (lock,O_WRONLY|O_CREAT,
  1199.              (int) mail_parameters (NIL,GET_LOCKPROTECTION,NIL));
  1200.     break;
  1201.       case EACCES:        /* protection fail, ignore if non-ex or old */
  1202.     if (!mail_parameters (NIL,GET_LOCKEACCESERROR,NIL)) {
  1203.       if (stat (lock,&sb) || (t > sb.st_ctime + LOCKTIMEOUT * 60))
  1204.         *lock = '\0';    /* assume no world write mail spool dir */
  1205.       break;
  1206.     }
  1207.       default:            /* some other failure */
  1208.     sprintf (tmp,"Error creating %s: %s",lock,strerror (errno));
  1209.     mm_log (tmp,WARN);    /* this is probably not good */
  1210.     *lock = '\0';        /* don't use lock files */
  1211.     break;
  1212.       }
  1213.     if (ld >= 0) {        /* if made a lock file */
  1214.                 /* make sure others can break the lock */
  1215.       chmod (lock,(int) mail_parameters (NIL,GET_LOCKPROTECTION,NIL));
  1216.       close (ld);        /* close the lock file */
  1217.     }
  1218. #endif
  1219.     if ((ld < 0) && *lock) {    /* if failed to make lock file and retry OK */
  1220.       if (!(i%15)) {
  1221.     sprintf (tmp,"Mailbox %s is locked, will override in %d seconds...",
  1222.          file,i);
  1223.     mm_log (tmp,WARN);
  1224.       }
  1225.       sleep (1);        /* wait 1 second before next try */
  1226.     }
  1227.   } while (i-- && ld < 0 && *lock);
  1228.                 /* open file */
  1229.   if ((fd = open (file,flags,mode)) >= 0) flock (fd,op);
  1230.   else {            /* open failed */
  1231.     j = errno;            /* preserve error code */
  1232.     if (*lock) unlink (lock);    /* flush the lock file if any */
  1233.     errno = j;            /* restore error code */
  1234.   }
  1235.   return fd;
  1236. }
  1237.  
  1238. /* Berkeley unlock and close mailbox
  1239.  * Accepts: file descriptor
  1240.  *        (optional) mailbox stream to check atime/mtime
  1241.  *        (optional) lock file name
  1242.  */
  1243.  
  1244. void bezerk_unlock (int fd,MAILSTREAM *stream,char *lock)
  1245. {
  1246.   struct stat sbuf;
  1247.   time_t tp[2];
  1248.   fstat (fd,&sbuf);        /* get file times */
  1249.                 /* if stream and csh would think new mail */
  1250.   if (stream && (sbuf.st_atime <= sbuf.st_mtime)) {
  1251.     tp[0] = time (0);        /* set atime to now */
  1252.                 /* set mtime to (now - 1) if necessary */
  1253.     tp[1] = tp[0] > sbuf.st_mtime ? sbuf.st_mtime : tp[0] - 1;
  1254.                 /* set the times, note change */
  1255.     if (!utime (LOCAL->name,tp)) LOCAL->filetime = tp[1];
  1256.   }
  1257.   flock (fd,LOCK_UN);        /* release flock'ers */
  1258.   close (fd);            /* close the file */
  1259.                 /* flush the lock file if any */
  1260.   if (lock && *lock) unlink (lock);
  1261. }
  1262.  
  1263. /* Berkeley mail parse and lock mailbox
  1264.  * Accepts: MAIL stream
  1265.  *        space to write lock file name
  1266.  *        type of locking operation
  1267.  * Returns: file descriptor if parse OK, mailbox is locked shared
  1268.  *        -1 if failure, stream aborted
  1269.  */
  1270.  
  1271. int bezerk_parse (MAILSTREAM *stream,char *lock,int op)
  1272. {
  1273.   int fd;
  1274.   long delta,i,j,is,is1;
  1275.   char c = '\n',*s,*s1,*t = NIL,*e;
  1276.   int ti = 0,zn = 0;
  1277.   long nmsgs = stream->nmsgs;
  1278.   long newcnt = 0;
  1279.   struct stat sbuf;
  1280.   STRING bs;
  1281.   MESSAGECACHE *elt;
  1282.   FILECACHE *m = NIL,*n = NIL;
  1283.   mailcache_t mc = (mailcache_t) mail_parameters (NIL,GET_CACHE,NIL);
  1284.   mail_lock (stream);        /* guard against recursion or pingers */
  1285.                 /* open and lock mailbox (shared OK) */
  1286.   if ((fd = bezerk_lock (LOCAL->name,LOCAL->ld ? O_RDWR : O_RDONLY,NIL,
  1287.              lock,op)) < 0) {
  1288.     sprintf (LOCAL->buf,"Mailbox open failed, aborted: %s",strerror (errno));
  1289.     mm_log (LOCAL->buf,ERROR);
  1290.     bezerk_abort (stream);
  1291.     mail_unlock (stream);
  1292.     return -1;
  1293.   }
  1294.   fstat (fd,&sbuf);        /* get status */
  1295.                 /* calculate change in size */
  1296.   if ((delta = sbuf.st_size - LOCAL->filesize) < 0) {
  1297.     sprintf (LOCAL->buf,"Mailbox shrank from %d to %d bytes, aborted",
  1298.          LOCAL->filesize,sbuf.st_size);
  1299.     mm_log (LOCAL->buf,ERROR);    /* this is pretty bad */
  1300.     bezerk_unlock (fd,stream,lock);
  1301.     bezerk_abort (stream);
  1302.     mail_unlock (stream);
  1303.     return -1;
  1304.   }
  1305.  
  1306.   else if (delta) {        /* get to that position in the file */
  1307.     lseek (fd,LOCAL->filesize,L_SET);
  1308.     s = s1 = LOCAL->buf;    /* initial read-in location */
  1309.     i = 0;            /* initial unparsed read-in count */
  1310.     do {
  1311.       i = min (CHUNK,delta);    /* calculate read-in size */
  1312.                 /* increase the read-in buffer if necessary */
  1313.       if ((j = i + (s1 - s)) >= LOCAL->buflen) {
  1314.     is = s - LOCAL->buf;    /* note former start of message position */
  1315.     is1 = s1 - LOCAL->buf;    /* and start of new data position */
  1316.     if (s1 - s) fs_resize ((void **) &LOCAL->buf,(LOCAL->buflen = j) + 1);
  1317.     else {            /* fs_resize would do an unnecessary copy */
  1318.       fs_give ((void **) &LOCAL->buf);
  1319.       LOCAL->buf = (char *) fs_get ((LOCAL->buflen = j) + 1);
  1320.     }
  1321.     s = LOCAL->buf + is;    /* new start of message */
  1322.     s1 = LOCAL->buf + is1;    /* new start of new data */
  1323.       }
  1324.       s1[i] = '\0';        /* tie off chunk */
  1325.       if (read (fd,s1,i) < 0) {    /* read a chunk of new text */
  1326.     sprintf (LOCAL->buf,"Error reading mail file: %s",strerror (errno));
  1327.     mm_log (LOCAL->buf,ERROR);
  1328.     bezerk_unlock (fd,stream,lock);
  1329.     bezerk_abort (stream);
  1330.     mail_unlock (stream);
  1331.     return -1;
  1332.       }
  1333.       delta -= i;        /* account for data read in */
  1334.       if (c) {            /* validate newly-appended data */
  1335.                 /* skip leading whitespace */
  1336.     while ((*s == '\n') || (*s == ' ') || (*s == '\t')) {
  1337.       c = *s++;        /* yes, skip the damn thing */
  1338.       s1++;
  1339.       if (!--i) break;    /* only whitespace was appended?? */
  1340.     }
  1341.                 /* see new data is valid */
  1342.     if (c == '\n') VALID (s,t,ti,zn);
  1343.         if (!ti) {        /* invalid data? */
  1344.       char tmp[MAILTMPLEN];
  1345.       sprintf (tmp,"Unexpected changes to mailbox (try restarting): %.20s",
  1346.            s);
  1347.       mm_log (tmp,ERROR);
  1348.       bezerk_unlock (fd,stream,lock);
  1349.       bezerk_abort (stream);
  1350.       mail_unlock (stream);
  1351.       return -1;
  1352.     }
  1353.     c = NIL;        /* don't need to do this again */
  1354.       }
  1355.  
  1356.                 /* found end of message or end of data? */
  1357.       while ((e = bezerk_eom (s,s1,i)) || !delta) {
  1358.     nmsgs++;        /* yes, have a new message */
  1359.                 /* calculate message length */
  1360.     j = ((e ? e : s1 + i) - s) - 1;
  1361.     if (m) {        /* new cache needed, have previous data? */
  1362.       n->header = (char *) fs_get (sizeof (FILECACHE) + j + 3);
  1363.       n = (FILECACHE *) n->header;
  1364.     }
  1365.     else m = n = (FILECACHE *) fs_get (sizeof (FILECACHE) + j + 3);
  1366.                 /* copy message data */
  1367.     memcpy (n->internal,s,j);
  1368.                 /* ensure ends with newline */
  1369.     if (s[j-1] != '\n') n->internal[j++] = '\n';
  1370.     n->internal[j] = '\0';
  1371.     n->header = NIL;    /* initially no link */
  1372.     n->headersize = j;    /* stash away buffer length */
  1373.     if (e) {        /* saw end of message? */
  1374.       i -= e - s1;        /* new unparsed data count */
  1375.       s = s1 = e;        /* advance to new message */
  1376.     }
  1377.     else break;        /* else punt this loop */
  1378.       }
  1379.       if (delta) {        /* end of message not found? */
  1380.     s1 += i;        /* end of unparsed data */
  1381.     if (s != LOCAL->buf){    /* message doesn't begin at buffer? */
  1382.       i = s1 - s;        /* length of message so far */
  1383.       memmove (LOCAL->buf,s,i);
  1384.       s = LOCAL->buf;    /* message now starts at buffer origin */
  1385.       s1 = s + i;        /* calculate new end of unparsed data */
  1386.     }
  1387.       }
  1388.     } while (delta);        /* until nothing more new to read */
  1389.   }
  1390.   else {            /* no change, don't babble if never got time */
  1391.     if (LOCAL->filetime && LOCAL->filetime != sbuf.st_mtime)
  1392.       mm_log ("New mailbox modification time but apparently no changes",WARN);
  1393.   }
  1394.   (*mc) (stream,nmsgs,CH_SIZE);    /* expand the primary cache */
  1395.   if (nmsgs>=LOCAL->cachesize) {/* need to expand cache? */
  1396.                 /* number of messages plus room to grow */
  1397.     LOCAL->cachesize = nmsgs + CACHEINCREMENT;
  1398.     if (LOCAL->msgs)        /* resize if already have a cache */
  1399.       fs_resize ((void **) &LOCAL->msgs,LOCAL->cachesize*sizeof (FILECACHE *));
  1400.     else LOCAL->msgs =        /* create new cache */
  1401.       (FILECACHE **) fs_get (LOCAL->cachesize * sizeof (FILECACHE *));
  1402.   }
  1403.   if (LOCAL->buflen > CHUNK) {    /* maybe move where the buffer is in memory*/
  1404.     fs_give ((void **) &LOCAL->buf);
  1405.     LOCAL->buf = (char *) fs_get ((LOCAL->buflen = CHUNK) + 1);
  1406.   }
  1407.  
  1408.   for (i = stream->nmsgs, n = m; i < nmsgs; i++) {
  1409.     LOCAL->msgs[i] = m = n;    /* set cache, and next cache pointer */
  1410.     n = (FILECACHE *) n->header;
  1411.     /* This is a bugtrap for bogons in the new message cache, which may happen
  1412.      * if memory is corrupted.  Note that in the case of a totally empty
  1413.      * message, a newline is appended and counts adjusted.
  1414.      */
  1415.     ti = NIL;            /* valid header not found */
  1416.     if (s = m->internal) VALID (s,t,ti,zn);
  1417.     if (!ti) fatal ("Bogus entry in new cache list");
  1418.                 /* pointer to message header */
  1419.     if (s = strchr (t++,'\n')) m->header = ++s;
  1420.     else {            /* probably totally empty message */
  1421.       strcat (t-1,"\n");    /* append newline */
  1422.       m->headersize++;        /* adjust count */
  1423.       m->header = s = strchr (t-1,'\n') + 1;
  1424.     }
  1425.     m->headersize -= m->header - m->internal;
  1426.     m->body = NIL;        /* assume no body as yet */
  1427.     m->bodysize = 0;
  1428.                 /* instantiate elt */
  1429.     (elt = mail_elt (stream,i+1))->valid = T;
  1430.     newcnt++;            /* assume recent by default */
  1431.     elt->recent = T;
  1432.                 /* calculate initial Status/X-Status lines */
  1433.     bezerk_update_status (m->status,elt);
  1434.                 /* generate plausable IMAPish date string */
  1435.     LOCAL->buf[2] = LOCAL->buf[6] = LOCAL->buf[20] = '-';
  1436.     LOCAL->buf[11] = ' ';
  1437.     LOCAL->buf[14] = LOCAL->buf[17] = ':';
  1438.                 /* dd */
  1439.     LOCAL->buf[0] = t[ti - 3]; LOCAL->buf[1] = t[ti - 2];
  1440.                 /* mmm */
  1441.     LOCAL->buf[3] = t[ti - 7]; LOCAL->buf[4] = t[ti - 6];
  1442.     LOCAL->buf[5] = t[ti - 5];
  1443.                 /* hh */
  1444.     LOCAL->buf[12] = t[ti]; LOCAL->buf[13] = t[ti + 1];
  1445.                 /* mm */
  1446.     LOCAL->buf[15] = t[ti + 3]; LOCAL->buf[16] = t[ti + 4];
  1447.     if (t[ti += 5] == ':') {    /* ss if present */
  1448.       LOCAL->buf[18] = t[++ti];
  1449.       LOCAL->buf[19] = t[++ti];
  1450.       ti++;            /* move to space */
  1451.     }
  1452.     else LOCAL->buf[18] = LOCAL->buf[19] = '0';
  1453.                 /* yy -- advance over timezone if necessary */
  1454.     if (zn == ++ti) ti += (((t[zn] == '+') || (t[zn] == '-')) ? 6 : 4);
  1455.     LOCAL->buf[7] = t[ti]; LOCAL->buf[8] = t[ti + 1];
  1456.     LOCAL->buf[9] = t[ti + 2]; LOCAL->buf[10] = t[ti + 3];
  1457.  
  1458.                 /* zzz */
  1459.     t = zn ? (t + zn) : "LCL";
  1460.     LOCAL->buf[21] = *t++; LOCAL->buf[22] = *t++; LOCAL->buf[23] = *t++;
  1461.     if ((LOCAL->buf[21] != '+') && (LOCAL->buf[21] != '-'))
  1462.       LOCAL->buf[24] = '\0';
  1463.     else {            /* numeric time zone */
  1464.       LOCAL->buf[24] = *t++; LOCAL->buf[25] = *t++;
  1465.       LOCAL->buf[26] = '\0'; LOCAL->buf[20] = ' ';
  1466.     }
  1467.                 /* set internal date */
  1468.     if (!mail_parse_date (elt,LOCAL->buf)) mm_log ("Unparsable date",WARN);
  1469.     e = NIL;            /* no status stuff yet */
  1470.     do switch (*(t = s)) {    /* look at header lines */
  1471.     case '\n':            /* end of header */
  1472.       m->body = ++s;        /* start of body is here */
  1473.       j = m->body - m->header;    /* new header size */
  1474.                 /* calculate body size */
  1475.       if (m->headersize >= j) m->bodysize = m->headersize - j;
  1476.       if (e) {            /* saw status poop? */
  1477.     *e++ = '\n';        /* patch in trailing newline */
  1478.     m->headersize = e - m->header;
  1479.       }
  1480.       else m->headersize = j;    /* set header size */
  1481.       s = NIL;            /* don't scan any further */
  1482.       break;
  1483.     case '\0':            /* end of message */
  1484.       if (e) {            /* saw status poop? */
  1485.     *e++ = '\n';        /* patch in trailing newline */
  1486.     m->headersize = e - m->header;
  1487.       }
  1488.       break;
  1489.  
  1490.     case 'X':            /* possible X-Status: line */
  1491.       if (s[1] == '-' && s[2] == 'S' && s[3] == 't' && s[4] == 'a' &&
  1492.       s[5] == 't' && s[6] == 'u' && s[7] == 's' && s[8] == ':') s += 2;
  1493.     case 'S':            /* possible Status: line */
  1494.       if (s[0] == 'S' && s[1] == 't' && s[2] == 'a' && s[3] == 't' &&
  1495.       s[4] == 'u' && s[5] == 's' && s[6] == ':') {
  1496.     if (!e) e = t;        /* note deletion point */
  1497.     s += 6;            /* advance to status flags */
  1498.     do switch (*s++) {    /* parse flags */
  1499.     case 'R':        /* message read */
  1500.       elt->seen = T;
  1501.       break;
  1502.     case 'O':        /* message old */
  1503.       if (elt->recent) {    /* don't do this more than once! */
  1504.         elt->recent = NIL;    /* not recent any longer... */
  1505.         newcnt--;
  1506.       }
  1507.       break;
  1508.     case 'D':        /* message deleted */
  1509.       elt->deleted = T;
  1510.       break;
  1511.     case 'F':        /* message flagged */
  1512.       elt ->flagged = T;
  1513.       break;
  1514.     case 'A':        /* message answered */
  1515.       elt ->answered = T;
  1516.       break;
  1517.     default:        /* some other crap */
  1518.       break;
  1519.     } while (*s && *s != '\n');
  1520.                 /* recalculate Status/X-Status lines */
  1521.     bezerk_update_status (m->status,elt);
  1522.     break;            /* all done */
  1523.       }
  1524.                 /* otherwise fall into default case */
  1525.  
  1526.     default:            /* anything else is uninteresting */
  1527.       if (e) {            /* have status stuff to worry about? */
  1528.     j = s - e;        /* yuck!!  calculate size of delete area */
  1529.                 /* blat remaining number of bytes down */
  1530.     memmove (e,s,m->header + m->headersize - s);
  1531.     m->headersize -= j;    /* update for new size */
  1532.     s = e;            /* back up pointer */
  1533.     e = NIL;        /* no more delete area */
  1534.                 /* tie off old cruft */
  1535.     *(m->header + m->headersize) = '\0';
  1536.       }
  1537.       break;
  1538.     } while (s && (s = strchr (s,'\n')) && s++);
  1539.                 /* get size including CR's  */
  1540.     INIT (&bs,mail_string,(void *) m->header,m->headersize);
  1541.     elt->rfc822_size = strcrlflen (&bs);
  1542.     INIT (&bs,mail_string,(void *) m->body,m->bodysize);
  1543.     elt->rfc822_size += strcrlflen (&bs); 
  1544.   }
  1545.   if (n) fatal ("Cache link-list inconsistency");
  1546.   while (i < LOCAL->cachesize) LOCAL->msgs[i++] = NIL;
  1547.                 /* update parsed file size and time */
  1548.   LOCAL->filesize = sbuf.st_size;
  1549.   LOCAL->filetime = sbuf.st_mtime;
  1550.   mail_exists (stream,nmsgs);    /* notify upper level of new mailbox size */
  1551.   mail_recent (stream,stream->recent + newcnt);
  1552.   if (newcnt) LOCAL->dirty = T;    /* mark dirty so O flags are set */
  1553.   return fd;            /* return the winnage */
  1554. }
  1555.  
  1556. /* Berkeley search for end of message
  1557.  * Accepts: start of message
  1558.  *        start of new data
  1559.  *        size of new data
  1560.  * Returns: pointer to start of new message if one found
  1561.  */
  1562.  
  1563. #define Word unsigned long
  1564.  
  1565. char *bezerk_eom (char *som,char *sod,long i)
  1566. {
  1567.   char *s = (sod > som) ? sod - 1 : sod;
  1568.   char *s1,*t;
  1569.   int ti,zn;
  1570.   union {
  1571.     unsigned long wd;
  1572.     char ch[9];
  1573.   } wdtest;
  1574.   while ((s > som) && *s-- != '\n');
  1575.   if (i > 50) {            /* don't do fast search if very few bytes */
  1576.                 /* constant for word testing */
  1577.     strcpy (wdtest.ch,"AAAA1234");
  1578.     if(wdtest.wd == 0x41414141){/* not a 32-bit word machine? */
  1579.       register Word m = 0x0a0a0a0a;
  1580.                 /* any characters before word boundary? */
  1581.       while ((long) s & 3) if (*s++ == '\n') {
  1582.     VALID (s,t,ti,zn);
  1583.     if (ti) return s;
  1584.       }
  1585.       i = (sod + i) - s;    /* total number of tries */
  1586.       do {            /* fast search for newline */
  1587.     if ((0x80808080 & (0x01010101 + (0x7f7f7f7f & ~(m ^ *(Word *) s)))) &&
  1588.                 /* find rightmost newline in word */
  1589.         ((*(s1 = s + 3) == '\n') || (*--s1 == '\n') ||
  1590.          (*--s1 == '\n') || (*--s1 == '\n'))) {
  1591.       s1++;            /* skip past newline */
  1592.       VALID (s1,t,ti,zn);    /* see if valid From line */
  1593.       if (ti) return s1;
  1594.     }
  1595.     s += 4;            /* try next word */
  1596.     i -= 4;            /* count a word checked */
  1597.       } while (i > 24);        /* continue until end of plausible string */
  1598.     }
  1599.   }
  1600.                 /* slow search - still plausible string? */
  1601.   while (i-- > 24) if (*s++ == '\n') {
  1602.     VALID (s,t,ti,zn);        /* if found start of message... */
  1603.     if (ti) return s;        /* return that pointer */
  1604.   }
  1605.   return NIL;
  1606. }
  1607.  
  1608. /* Berkeley extend mailbox to reserve worst-case space for expansion
  1609.  * Accepts: MAIL stream
  1610.  *        file descriptor
  1611.  *        error string
  1612.  * Returns: T if extend OK and have gone critical, NIL if should abort
  1613.  */
  1614.  
  1615. int bezerk_extend (MAILSTREAM *stream,int fd,char *error)
  1616. {
  1617.   struct stat sbuf;
  1618.   MESSAGECACHE *elt;
  1619.   FILECACHE *m;
  1620.   char tmp[MAILTMPLEN];
  1621.   int i,ok;
  1622.   long f;
  1623.   char *s;
  1624.   int retry;
  1625.                 /* calculate estimated size of mailbox */
  1626.   for (i = 0,f = 0; i < stream->nmsgs;) {
  1627.     m = LOCAL->msgs[i];        /* get cache pointer */
  1628.     elt = mail_elt (stream,++i);/* get elt, increment message */
  1629.                 /* if not expunging, or not deleted */
  1630.     if (!(error && elt->deleted))
  1631.       f += (m->header - m->internal) + m->headersize + m->bodysize + 1 +
  1632.     sizeof (STATUS) - (elt->seen+elt->deleted+elt->flagged+elt->answered);
  1633.   }
  1634.   mm_critical (stream);        /* go critical */
  1635.                 /* return now if file large enough */
  1636.   if (f <= LOCAL->filesize) return T;
  1637.   s = (char *) fs_get (f -= LOCAL->filesize);
  1638.   memset (s,0,f);        /* get a block of nulls */
  1639.                 /* get to end of file */
  1640.   lseek (fd,LOCAL->filesize,L_SET);
  1641.   do {
  1642.     retry = NIL;        /* no retry yet */
  1643.     if (!(ok = (write (fd,s,f) >= 0))) {
  1644.       i = errno;        /* note error before doing ftruncate */
  1645.                 /* restore prior file size */
  1646.       ftruncate (fd,LOCAL->filesize);
  1647.       fsync (fd);        /* is this necessary? */
  1648.       fstat (fd,&sbuf);        /* now get updated file time */
  1649.       LOCAL->filetime = sbuf.st_mtime;
  1650.                 /* punt if that's what main program wants */
  1651.       if (mm_diskerror (stream,i,NIL)) {
  1652.     mm_nocritical (stream);    /* exit critical */
  1653.     sprintf (tmp,"%s: %s",error ? error : "Unable to update mailbox",
  1654.          strerror (i));
  1655.     mm_notify (stream,tmp,WARN);
  1656.       }
  1657.       else retry = T;        /* set to retry */
  1658.     }
  1659.   } while (retry);        /* repeat if need to try again */
  1660.   fs_give ((void **) &s);    /* flush buffer of nulls */
  1661.   return ok;            /* return status */
  1662. }
  1663.  
  1664. /* Berkeley save mailbox
  1665.  * Accepts: MAIL stream
  1666.  *        mailbox file descriptor
  1667.  *
  1668.  * Mailbox must be readwrite and locked for exclusive access.
  1669.  */
  1670.  
  1671. void bezerk_save (MAILSTREAM *stream,int fd)
  1672. {
  1673.   struct stat sbuf;
  1674.   long i;
  1675.   int e;
  1676.   int retry;
  1677.   do {                /* restart point if failure */
  1678.     retry = NIL;        /* no need to retry yet */
  1679.                 /* start at beginning of file */
  1680.     lseek (fd,LOCAL->filesize = 0,L_SET);
  1681.                 /* loop through all messages */
  1682.     for (i = 1; i <= stream->nmsgs; i++) {
  1683.                 /* write message */
  1684.       if ((e = bezerk_write_message (fd,LOCAL->msgs[i-1])) < 0) {
  1685.     sprintf (LOCAL->buf,"Mailbox rewrite error: %s",strerror (e = errno));
  1686.     mm_log (LOCAL->buf,WARN);
  1687.     mm_diskerror (stream,e,T);
  1688.     retry = T;        /* must retry */
  1689.     break;            /* abort this particular try */
  1690.       }
  1691.       else LOCAL->filesize += e;/* count these bytes in data */
  1692.     }
  1693.     if (fsync (fd)) {        /* make sure the updates take */
  1694.       sprintf (LOCAL->buf,"Unable to sync mailbox: %s",strerror (e = errno));
  1695.       mm_log (LOCAL->buf,WARN);
  1696.       mm_diskerror (stream,e,T);
  1697.       retry = T;        /* oops */
  1698.     }
  1699.   } while (retry);        /* repeat if need to try again */
  1700.   ftruncate(fd,LOCAL->filesize);/* nuke any cruft after that */
  1701.   fsync (fd);            /* is this necessary? */
  1702.   fstat (fd,&sbuf);        /* now get updated file time */
  1703.   LOCAL->filetime = sbuf.st_mtime;
  1704.   LOCAL->dirty = NIL;        /* stream no longer dirty */
  1705.   mm_nocritical (stream);    /* exit critical */
  1706. }
  1707.  
  1708. /* Berkeley copy messages
  1709.  * Accepts: MAIL stream
  1710.  *        mailbox name
  1711.  * Returns: T if copy successful else NIL
  1712.  */
  1713.  
  1714. int bezerk_copy_messages (MAILSTREAM *stream,char *mailbox)
  1715. {
  1716.   char file[MAILTMPLEN],lock[MAILTMPLEN];
  1717.   struct stat sbuf;
  1718.   int fd;
  1719.   time_t tp[2];
  1720.   long i;
  1721.   int ok = T;
  1722.                 /* make sure valid mailbox */
  1723.   if (!bezerk_isvalid (mailbox,file)) switch (errno) {
  1724.   case ENOENT:            /* no such file? */
  1725.     mm_notify (stream,"[TRYCREATE] Must create mailbox before copy",NIL);
  1726.     return NIL;
  1727.   case 0:            /* merely empty file? */
  1728.     break;
  1729.   case EINVAL:
  1730.     sprintf (LOCAL->buf,"Invalid Berkeley-format mailbox name: %s",mailbox);
  1731.     mm_log (LOCAL->buf,ERROR);
  1732.     return NIL;
  1733.   default:
  1734.     sprintf (LOCAL->buf,"Not a Berkeley-format mailbox: %s",mailbox);
  1735.     mm_log (LOCAL->buf,ERROR);
  1736.     return NIL;
  1737.   }
  1738.   if ((fd = bezerk_lock (dummy_file (file,mailbox),O_WRONLY|O_APPEND|O_CREAT,
  1739.              S_IREAD|S_IWRITE,lock,LOCK_EX)) < 0) {
  1740.     sprintf (LOCAL->buf,"Can't open destination mailbox: %s",strerror (errno));
  1741.     mm_log (LOCAL->buf,ERROR);
  1742.     return NIL;
  1743.   }
  1744.   mm_critical (stream);        /* go critical */
  1745.   fstat (fd,&sbuf);        /* get current file size */
  1746.                 /* write all requested messages to mailbox */
  1747.   for (i = 1; ok && i <= stream->nmsgs; i++)
  1748.                 /* copy message if selected */
  1749.     if (mail_elt (stream,i)->sequence &&
  1750.     (bezerk_write_message (fd,LOCAL->msgs[i - 1]) < 0)) {
  1751.       sprintf (LOCAL->buf,"Message copy failed: %s",strerror (errno));
  1752.       mm_log (LOCAL->buf,ERROR);
  1753.       ftruncate (fd,sbuf.st_size);
  1754.       ok = NIL;
  1755.       break;
  1756.     }
  1757.   if (fsync (fd)) {        /* force out the update */
  1758.     sprintf (LOCAL->buf,"Message copy sync failed: %s",strerror (errno));
  1759.     mm_log (LOCAL->buf,ERROR);
  1760.     ftruncate (fd,sbuf.st_size);
  1761.     ok = NIL;            /* oops */
  1762.   }
  1763.   tp[0] = sbuf.st_atime;    /* preserve atime */
  1764.   tp[1] = time (0);        /* set mtime to now */
  1765.   utime (file,tp);        /* set the times */
  1766.   bezerk_unlock (fd,NIL,lock);    /* unlock and close mailbox */
  1767.   mm_nocritical (stream);    /* release critical */
  1768.   return ok;            /* return whether or not succeeded */
  1769. }
  1770.  
  1771. /* Berkeley write message to mailbox
  1772.  * Accepts: file descriptor
  1773.  *        local cache for this message
  1774.  * Returns: number of bytes written or -1 if error
  1775.  *
  1776.  * This routine is the reason why the local cache has a copy of the status.
  1777.  * We can be called to dump out the mailbox as part of a stream recycle, since
  1778.  * we don't write out the mailbox when flags change and hence an update may be
  1779.  * needed.  However, at this point the elt has already become history, so we
  1780.  * can't use any information other than what is local to us.
  1781.  */
  1782.  
  1783. int bezerk_write_message (int fd,FILECACHE *m)
  1784. {
  1785.   struct iovec iov[16];
  1786.   int i = 0;
  1787.   iov[i].iov_base = m->internal;/* pointer/counter to headers */
  1788.                 /* length of internal + message headers */
  1789.   iov[i].iov_len = (m->header + m->headersize) - m->internal;
  1790.                 /* suppress extra newline if present */
  1791.   if (((char *) iov[i].iov_base)[iov[i].iov_len - 2] == '\n')
  1792.     iov[i++].iov_len--;
  1793.   else i++;            /* unlikely but... */
  1794.   iov[i].iov_base = m->status;    /* pointer/counter to status */
  1795.   iov[i++].iov_len = strlen (m->status);
  1796.   if (m->bodysize) {        /* only if a non-empty body */
  1797.     iov[i].iov_base = m->body;    /* pointer/counter to text body */
  1798.     iov[i++].iov_len = m->bodysize;
  1799.   }
  1800.   iov[i].iov_base = "\n";    /* pointer/counter to extra newline */
  1801.   iov[i++].iov_len = 1;
  1802.   return writev (fd,iov,i);
  1803. }
  1804.  
  1805. /* Berkeley update status string
  1806.  * Accepts: destination string to write
  1807.  *        message cache entry
  1808.  */
  1809.  
  1810. void bezerk_update_status (char *status,MESSAGECACHE *elt)
  1811. {
  1812.   /* This used to be an sprintf(), but thanks to certain cretinous C libraries
  1813.      with horribly slow implementations of sprintf() I had to change it to this
  1814.      mess.  At least it should be fast. */
  1815.   char *t = status + 8;
  1816.   status[0] = 'S'; status[1] = 't'; status[2] = 'a'; status[3] = 't';
  1817.   status[4] = 'u'; status[5] = 's'; status[6] = ':';  status[7] = ' ';
  1818.   if (elt->seen) *t++ = 'R'; *t++ = 'O'; *t++ = '\n';
  1819.   *t++ = 'X'; *t++ = '-'; *t++ = 'S'; *t++ = 't'; *t++ = 'a'; *t++ = 't';
  1820.   *t++ = 'u'; *t++ = 's'; *t++ = ':'; *t++ = ' ';
  1821.   if (elt->deleted) *t++ = 'D'; if (elt->flagged) *t++ = 'F';
  1822.   if (elt->answered) *t++ = 'A';
  1823.   *t++ = '\n'; *t++ = '\n'; *t++ = '\0';
  1824. }
  1825.  
  1826. /* Parse flag list
  1827.  * Accepts: MAIL stream
  1828.  *        flag list as a character string
  1829.  * Returns: flag command list
  1830.  */
  1831.  
  1832.  
  1833. short bezerk_getflags (MAILSTREAM *stream,char *flag)
  1834. {
  1835.   char *t,tmp[MAILTMPLEN],err[MAILTMPLEN];
  1836.   short f = 0;
  1837.   short i,j;
  1838.   if (flag && *flag) {        /* no-op if no flag string */
  1839.                 /* check if a list and make sure valid */
  1840.     if ((i = (*flag == '(')) ^ (flag[strlen (flag)-1] == ')')) {
  1841.       mm_log ("Bad flag list",ERROR);
  1842.       return NIL;
  1843.     }
  1844.                 /* copy the flag string w/o list construct */
  1845.     strncpy (tmp,flag+i,(j = strlen (flag) - (2*i)));
  1846.     tmp[j] = '\0';
  1847.     t = ucase (tmp);        /* uppercase only from now on */
  1848.  
  1849.     while (t && *t) {        /* parse the flags */
  1850.       if (*t == '\\') {        /* system flag? */
  1851.     switch (*++t) {        /* dispatch based on first character */
  1852.     case 'S':        /* possible \Seen flag */
  1853.       if (t[1] == 'E' && t[2] == 'E' && t[3] == 'N') i = fSEEN;
  1854.       t += 4;        /* skip past flag name */
  1855.       break;
  1856.     case 'D':        /* possible \Deleted flag */
  1857.       if (t[1] == 'E' && t[2] == 'L' && t[3] == 'E' && t[4] == 'T' &&
  1858.           t[5] == 'E' && t[6] == 'D') i = fDELETED;
  1859.       t += 7;        /* skip past flag name */
  1860.       break;
  1861.     case 'F':        /* possible \Flagged flag */
  1862.       if (t[1] == 'L' && t[2] == 'A' && t[3] == 'G' && t[4] == 'G' &&
  1863.           t[5] == 'E' && t[6] == 'D') i = fFLAGGED;
  1864.       t += 7;        /* skip past flag name */
  1865.       break;
  1866.     case 'A':        /* possible \Answered flag */
  1867.       if (t[1] == 'N' && t[2] == 'S' && t[3] == 'W' && t[4] == 'E' &&
  1868.           t[5] == 'R' && t[6] == 'E' && t[7] == 'D') i = fANSWERED;
  1869.       t += 8;        /* skip past flag name */
  1870.       break;
  1871.     default:        /* unknown */
  1872.       i = 0;
  1873.       break;
  1874.     }
  1875.                 /* add flag to flags list */
  1876.     if (i && ((*t == '\0') || (*t++ == ' '))) f |= i;
  1877.       }
  1878.       else {            /* no user flags yet */
  1879.     t = strtok (t," ");    /* isolate flag name */
  1880.     sprintf (err,"Unknown flag: %.80s",t);
  1881.     t = strtok (NIL," ");    /* get next flag */
  1882.     mm_log (err,ERROR);
  1883.       }
  1884.     }
  1885.   }
  1886.   return f;
  1887. }
  1888.  
  1889. /* Search support routines
  1890.  * Accepts: MAIL stream
  1891.  *        message number
  1892.  *        pointer to additional data
  1893.  * Returns: T if search matches, else NIL
  1894.  */
  1895.  
  1896.  
  1897. char bezerk_search_all (MAILSTREAM *stream,long msgno,char *d,long n)
  1898. {
  1899.   return T;            /* ALL always succeeds */
  1900. }
  1901.  
  1902.  
  1903. char bezerk_search_answered (MAILSTREAM *stream,long msgno,char *d,long n)
  1904. {
  1905.   return mail_elt (stream,msgno)->answered ? T : NIL;
  1906. }
  1907.  
  1908.  
  1909. char bezerk_search_deleted (MAILSTREAM *stream,long msgno,char *d,long n)
  1910. {
  1911.   return mail_elt (stream,msgno)->deleted ? T : NIL;
  1912. }
  1913.  
  1914.  
  1915. char bezerk_search_flagged (MAILSTREAM *stream,long msgno,char *d,long n)
  1916. {
  1917.   return mail_elt (stream,msgno)->flagged ? T : NIL;
  1918. }
  1919.  
  1920.  
  1921. char bezerk_search_keyword (MAILSTREAM *stream,long msgno,char *d,long n)
  1922. {
  1923.   return NIL;            /* keywords not supported yet */
  1924. }
  1925.  
  1926.  
  1927. char bezerk_search_new (MAILSTREAM *stream,long msgno,char *d,long n)
  1928. {
  1929.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  1930.   return (elt->recent && !elt->seen) ? T : NIL;
  1931. }
  1932.  
  1933. char bezerk_search_old (MAILSTREAM *stream,long msgno,char *d,long n)
  1934. {
  1935.   return mail_elt (stream,msgno)->recent ? NIL : T;
  1936. }
  1937.  
  1938.  
  1939. char bezerk_search_recent (MAILSTREAM *stream,long msgno,char *d,long n)
  1940. {
  1941.   return mail_elt (stream,msgno)->recent ? T : NIL;
  1942. }
  1943.  
  1944.  
  1945. char bezerk_search_seen (MAILSTREAM *stream,long msgno,char *d,long n)
  1946. {
  1947.   return mail_elt (stream,msgno)->seen ? T : NIL;
  1948. }
  1949.  
  1950.  
  1951. char bezerk_search_unanswered (MAILSTREAM *stream,long msgno,char *d,long n)
  1952. {
  1953.   return mail_elt (stream,msgno)->answered ? NIL : T;
  1954. }
  1955.  
  1956.  
  1957. char bezerk_search_undeleted (MAILSTREAM *stream,long msgno,char *d,long n)
  1958. {
  1959.   return mail_elt (stream,msgno)->deleted ? NIL : T;
  1960. }
  1961.  
  1962.  
  1963. char bezerk_search_unflagged (MAILSTREAM *stream,long msgno,char *d,long n)
  1964. {
  1965.   return mail_elt (stream,msgno)->flagged ? NIL : T;
  1966. }
  1967.  
  1968.  
  1969. char bezerk_search_unkeyword (MAILSTREAM *stream,long msgno,char *d,long n)
  1970. {
  1971.   return T;            /* keywords not supported yet */
  1972. }
  1973.  
  1974.  
  1975. char bezerk_search_unseen (MAILSTREAM *stream,long msgno,char *d,long n)
  1976. {
  1977.   return mail_elt (stream,msgno)->seen ? NIL : T;
  1978. }
  1979.  
  1980. char bezerk_search_before (MAILSTREAM *stream,long msgno,char *d,long n)
  1981. {
  1982.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  1983.   return (char) ((long) ((elt->year << 9) + (elt->month << 5) + elt->day) < n);
  1984. }
  1985.  
  1986.  
  1987. char bezerk_search_on (MAILSTREAM *stream,long msgno,char *d,long n)
  1988. {
  1989.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  1990.   return (char) (((elt->year << 9) + (elt->month << 5) + elt->day) == n);
  1991. }
  1992.  
  1993.  
  1994. char bezerk_search_since (MAILSTREAM *stream,long msgno,char *d,long n)
  1995. {
  1996.                 /* everybody interprets "since" as .GE. */
  1997.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  1998.   return (char)((long) ((elt->year << 9) + (elt->month << 5) + elt->day) >= n);
  1999. }
  2000.  
  2001.  
  2002. char bezerk_search_body (MAILSTREAM *stream,long msgno,char *d,long n)
  2003. {
  2004.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  2005.   return search (m->body,m->bodysize,d,n);
  2006. }
  2007.  
  2008.  
  2009. char bezerk_search_subject (MAILSTREAM *stream,long msgno,char *d,long n)
  2010. {
  2011.   char *s = bezerk_fetchstructure (stream,msgno,NIL)->subject;
  2012.   return s ? search (s,strlen (s),d,n) : NIL;
  2013. }
  2014.  
  2015.  
  2016. char bezerk_search_text (MAILSTREAM *stream,long msgno,char *d,long n)
  2017. {
  2018.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  2019.   return search (m->header,m->headersize,d,n) ||
  2020.     bezerk_search_body (stream,msgno,d,n);
  2021. }
  2022.  
  2023. char bezerk_search_bcc (MAILSTREAM *stream,long msgno,char *d,long n)
  2024. {
  2025.   ADDRESS *a = bezerk_fetchstructure (stream,msgno,NIL)->bcc;
  2026.   LOCAL->buf[0] = '\0';        /* initially empty string */
  2027.                 /* get text for address */
  2028.   rfc822_write_address (LOCAL->buf,a);
  2029.   return search (LOCAL->buf,(long) strlen (LOCAL->buf),d,n);
  2030. }
  2031.  
  2032.  
  2033. char bezerk_search_cc (MAILSTREAM *stream,long msgno,char *d,long n)
  2034. {
  2035.   ADDRESS *a = bezerk_fetchstructure (stream,msgno,NIL)->cc;
  2036.   LOCAL->buf[0] = '\0';        /* initially empty string */
  2037.                 /* get text for address */
  2038.   rfc822_write_address (LOCAL->buf,a);
  2039.   return search (LOCAL->buf,(long) strlen (LOCAL->buf),d,n);
  2040. }
  2041.  
  2042.  
  2043. char bezerk_search_from (MAILSTREAM *stream,long msgno,char *d,long n)
  2044. {
  2045.   ADDRESS *a = bezerk_fetchstructure (stream,msgno,NIL)->from;
  2046.   LOCAL->buf[0] = '\0';        /* initially empty string */
  2047.                 /* get text for address */
  2048.   rfc822_write_address (LOCAL->buf,a);
  2049.   return search (LOCAL->buf,(long) strlen (LOCAL->buf),d,n);
  2050. }
  2051.  
  2052.  
  2053. char bezerk_search_to (MAILSTREAM *stream,long msgno,char *d,long n)
  2054. {
  2055.   ADDRESS *a = bezerk_fetchstructure (stream,msgno,NIL)->to;
  2056.   LOCAL->buf[0] = '\0';        /* initially empty string */
  2057.                 /* get text for address */
  2058.   rfc822_write_address (LOCAL->buf,a);
  2059.   return search (LOCAL->buf,(long) strlen (LOCAL->buf),d,n);
  2060. }
  2061.  
  2062. /* Search parsers */
  2063.  
  2064.  
  2065. /* Parse a date
  2066.  * Accepts: function to return
  2067.  *        pointer to date integer to return
  2068.  * Returns: function to return
  2069.  */
  2070.  
  2071. search_t bezerk_search_date (search_t f,long *n)
  2072. {
  2073.   long i;
  2074.   char *s;
  2075.   MESSAGECACHE elt;
  2076.                 /* parse the date and return fn if OK */
  2077.   return (bezerk_search_string (f,&s,&i) && mail_parse_date (&elt,s) &&
  2078.       (*n = (elt.year << 9) + (elt.month << 5) + elt.day)) ? f : NIL;
  2079. }
  2080.  
  2081. /* Parse a flag
  2082.  * Accepts: function to return
  2083.  *        pointer to string to return
  2084.  * Returns: function to return
  2085.  */
  2086.  
  2087. search_t bezerk_search_flag (search_t f,char **d)
  2088. {
  2089.                 /* get a keyword, return if OK */
  2090.   return (*d = strtok (NIL," ")) ? f : NIL;
  2091. }
  2092.  
  2093.  
  2094. /* Parse a string
  2095.  * Accepts: function to return
  2096.  *        pointer to string to return
  2097.  *        pointer to string length to return
  2098.  * Returns: function to return
  2099.  */
  2100.  
  2101. search_t bezerk_search_string (search_t f,char **d,long *n)
  2102. {
  2103.   char *end = " ";
  2104.   char *c = strtok (NIL,"");    /* remainder of criteria */
  2105.   if (!c) return NIL;        /* missing argument */
  2106.   switch (*c) {            /* see what the argument is */
  2107.   case '{':            /* literal string */
  2108.     *n = strtol (c+1,d,10);    /* get its length */
  2109.     if ((*(*d)++ == '}') && (*(*d)++ == '\015') && (*(*d)++ == '\012') &&
  2110.     (!(*(c = *d + *n)) || (*c == ' '))) {
  2111.       char e = *--c;
  2112.       *c = DELIM;        /* make sure not a space */
  2113.       strtok (c," ");        /* reset the strtok mechanism */
  2114.       *c = e;            /* put character back */
  2115.       break;
  2116.     }
  2117.   case '\0':            /* catch bogons */
  2118.   case ' ':
  2119.     return NIL;
  2120.   case '"':            /* quoted string */
  2121.     if (strchr (c+1,'"')) end = "\"";
  2122.     else return NIL;
  2123.   default:            /* atomic string */
  2124.     if (*d = strtok (c,end)) *n = strlen (*d);
  2125.     else return NIL;
  2126.     break;
  2127.   }
  2128.   return f;
  2129. }
  2130.